package core.android.tools;

import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextWatcher;
import android.widget.EditText;

import java.math.BigDecimal;

/**
 * @作者: XQ
 * @创建时间：16/5/7 下午4:39
 * @类说明: 金钱格式限制
 */
public class AKMoneyUtil {
    final static int digit = 2;
    final static int maxLength = 7;


    /**
     * 设置金额格式化限制
     *
     * @param editText
     */
    public static void setEditTextFilter(EditText editText) {
        editText.setFilters(new InputFilter[]{AKMoneyUtil.lengthfilter});
    }


    /**
     * 限制小数点后只能有两位
     */
    /**
     * 设置小数位数控制
     */
    public static InputFilter lengthfilter = new InputFilter() {
        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            AK.d("source=" + source);
            // 删除等特殊字符，直接返回
            if ("".equals(source.toString())) {
                return null;
            }
            String toValue = dest.toString() + source;
            AK.d("toValue=" + toValue);
            String[] splitArray = toValue.split("\\.");
            AK.d("长度:" + splitArray.length);
            switch (splitArray.length) {
                case 1:
                    AK.d("整数位:" + splitArray[0]);
                    if (splitArray[0].length() == maxLength) {
                        return source;
                    }
                    if (splitArray[0].length() > maxLength) {
                        return "";
                    }
                    break;
                case 2:
                    AK.d(".之后的数值:" + splitArray[1]);
                    if (splitArray[1].length() == digit) {
                        return source;
                    }
                    if (splitArray[1].length() >= digit) {
                        return "";
                    }
                    break;
            }
            return null;
        }
    };


    /**
     * 尝试获取金额
     *
     * @param str
     * @return
     */
    public static String tryGetMoney(String str) {
        if (str == null) {
            return "";
        }
        StringBuffer mayMoney = new StringBuffer();
        for (char s : str.toCharArray()) {
            if (Character.isDigit(s)) {
                mayMoney.append(s);
            } else if ('.' == s) {
                mayMoney.append(".");
            }
        }
        if (mayMoney.length() > 0) {
            try {
                BigDecimal topayMoney = new BigDecimal(mayMoney.toString()).setScale(2, BigDecimal.ROUND_HALF_UP);
                return String.valueOf(topayMoney);
            } catch (Exception e) {
                System.out.println("获取金额失败 mayMoney=" + mayMoney);
            }
        }
        return "";
    }


    static int good_maxLength = 8;
    static InputFilter goodLengthfilter = new InputFilter() {
        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            AK.d("source=" + source);
            // 删除等特殊字符，直接返回
            if ("".equals(source.toString())) {
                return null;
            }
            String toValue = dest.toString() + source;
            AK.d("toValue=" + toValue);
            String[] splitArray = toValue.split("\\.");
            AK.d("长度:" + splitArray.length);
            switch (splitArray.length) {
                case 1:
                    AK.d("整数位:" + splitArray[0]);
                    if (splitArray[0].length() == good_maxLength) {
                        return source;
                    }
                    if (splitArray[0].length() > good_maxLength) {
                        return "";
                    }
                    break;
                case 2:
                    AK.d(".之后的数值:" + splitArray[1]);
                    if (splitArray[1].length() == digit) {
                        return source;
                    }
                    if (splitArray[1].length() >= digit) {
                        return "";
                    }
                    break;
            }
            return null;
        }
    };


    /**
     * 设置商品价格格式化限制,限制小数点后只能有两位
     */
    public static void setGoodEditTextFilter(EditText editText, int good_maxLength) {
        AKMoneyUtil.good_maxLength = good_maxLength;
        editText.setFilters(new InputFilter[]{AKMoneyUtil.goodLengthfilter});
    }

    /**
     * 获取银行卡最后4位
     *
     * @param bankNumber
     */
    public static String getBankLastNum(String bankNumber) {
        String bankNamLast = "";
        if (!AKTextUtil.isEmpty(bankNumber) && bankNumber.length() > 4) {
            bankNamLast = bankNumber.substring(bankNumber.length() - 4, bankNumber.length());
        }
        return bankNamLast;
    }

    /**
     * 银行卡：输入四位数字后自动补充空格
     * 使用注意，取出的卡号要去除空格：
     * final String cardNum = edt_card_number.getText().toString().replaceAll(" +","");
     *
     * @param editText
     */
    public static void setBankNumberInput(final EditText editText) {
        editText.addTextChangedListener(new TextWatcher() {

            private int oldLength = 0;
            private boolean isChange = true;
            private int curLength = 0;
            private int emptyNumB = 0;
            private int emptyNumA = 0;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                oldLength = s.length();
//                AKLog.i( "未改变长度: " + oldLength);
                emptyNumB = 0;
                for (int i = 0; i < s.toString().length(); i++) {
                    if (s.charAt(i) == ' ') emptyNumB++;
                }
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                curLength = s.length();
//                AKLog.i( "当前长度: " + curLength);
                if (curLength == oldLength || curLength <= 3) {
                    isChange = false;
                } else {
                    isChange = true;
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (isChange) {
                    int selectIndex = editText.getSelectionEnd();//获取光标位置
                    String content = s.toString().replaceAll(" ", "");
//                    AKLog.i("content:" + content);
                    StringBuffer sb = new StringBuffer(content);
                    //遍历加空格
                    int index = 1;
                    emptyNumA = 0;
                    for (int i = 0; i < content.length(); i++) {
                        if ((i + 1) % 4 == 0) {
                            sb.insert(i + index, " ");
                            index++;
                            emptyNumA++;
                        }
                    }
//                    AKLog.i("result content:" + sb.toString());
                    String result = sb.toString();
                    if (result.endsWith(" ")) {
                        result = result.substring(0, result.length() - 1);
                    }
                    editText.setText(result);
                    if (emptyNumA > emptyNumB)
                        selectIndex = selectIndex + (emptyNumA - emptyNumB);
                    //处理光标位置
                    if (selectIndex > result.length() || selectIndex + 1 == result.length()) {
                        selectIndex = result.length();
                    } else if (selectIndex < 0) {
                        selectIndex = 0;
                    }
                    editText.setSelection(selectIndex);
                    isChange = false;
                }
            }
        });
    }

    /**
     * 格式化银行卡号
     * 每4位添加空格
     *
     * @param num
     * @return
     */
    public static String getCardNumer(String num) {
        if (AKTextUtil.isEmpty(num)) {
            return "";
        }
        StringBuffer buffer = new StringBuffer();
        char[] chars = num.toCharArray();
        for (int i = 1; i <= chars.length; i++) {
            buffer.append(chars[i - 1]);
            if (i % 4 == 0) {
                buffer.append(" ");
            }
        }
        AK.e(buffer.toString());
        return buffer.toString();
    }

}
